﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: CrMosk
 * Дата: 10.05.2013
 * Время: 14:03
 * 
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
#define ExportRTF
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;

namespace Region.Utils
{
  
  /// <summary>
  /// Экспорт RTF документов.
  /// </summary>
  public class ExportRTF: Export// Неподдерживает вставку таблиц
    {
        static String DataCoding(byte[] Data)
        {            
            String S="";            
            foreach(byte b in Data) S+=b.ToString("X2");
            return S;
        }
        static String RTF_ReplaceBookmark(String RTF, Dictionary<String, Object> Poles)
        {
            //String S1 = DataCoding(new byte[] { 1, 2, 3, 4, 5, 200, 202, 203 });
            foreach(KeyValuePair<String, Object> Pole in Poles)
            {
                String Pat = @"{\\\*\\bkmkstart[\s]*" + Pole.Key + @"[\s]*}[\s\S]*{\\\*\\bkmkend[\s]*" + Pole.Key + @"[\s]*}";
                String Val="";
                if (Pole.Value as String != null) Val = ((String)Pole.Value);
                else if (Pole.Value as Bitmap != null) 
                {
                    var st = new MemoryStream();
                    ((Bitmap)Pole.Value).Save(st, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Val = @"{\pict\jpegblip "+DataCoding(st.GetBuffer())+"}";
                }                
                //Match m = Regex.Match(RTF, Pat);
                RTF = Regex.Replace(RTF, Pat, Val);
            }            
            return RTF;
        }
        static String RTF_ReplaceText(String RTF, Dictionary<String, Object> Poles)
        {
            //String S1 = DataCoding(new byte[] { 1, 2, 3, 4, 5, 200, 202, 203 });
            foreach(KeyValuePair<String, Object> Pole in Poles)
            {
                String Pat = "%" + Pole.Key + "%";
                String Val="";
                if (Pole.Value as String != null) Val = ((String)Pole.Value);
                else if (Pole.Value as Bitmap != null)
                {
                    var st = new MemoryStream();
                    ((Bitmap)Pole.Value).Save(st, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Val = @"{\pict\jpegblip "+DataCoding(st.GetBuffer())+"}";
                }                
                //Match m = Regex.Match(RTF, Pat);

                RTF = Regex.Replace(RTF, Pat, Val);

            }            
            return RTF;
        }
        /*static bool ExportRTF(String Template, String Out, Dictionary<String, Object> Poles)
        {
            //using (Stream f1 = (file.Extension.ToLower() == ".gz") ? (Stream)(new GZipStream(File.OpenRead(file.FullName), CompressionMode.Decompress)) : (Stream)(File.OpenRead(file.FullName)))            
            using (Stream f1 = (Stream)(File.OpenRead(Template)))
            { 
                byte[] Buff = new byte[f1.Length];
                f1.Read(Buff,0,(Int32)f1.Length);
                return ExportRTF(Buff, Out, Poles);
            }+
        }*/
        public override bool Save(TaskManager.Task task = null)        
        {
            byte[] Temp = Utils.Compression.DecodeGZ(Template);
            String RTF = Encoding.GetEncoding("windows-1251").GetString(Temp);
            RTF = RTF_ReplaceBookmark(RTF, Poles);
            RTF = RTF_ReplaceText(RTF, Poles);
            byte[] WriteBuff = Encoding.GetEncoding("windows-1251").GetBytes(RTF);
            using (Stream f2 = File.Create(OutFile))
            {
                f2.Write(WriteBuff, 0, WriteBuff.Length);
                return true;
            }            
        }

    }
}
